# # This is a sample Python script.
#
# # Press ⌃R to execute it or replace it with your code.
# # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
#
#
# def print_hi(name):
#     # Use a breakpoint in the code line below to debug your script.
#     print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.
#
#
# # Press the green button in the gutter to run the script.
# if __name__ == '__main__':
#     print_hi('PyCharm')
#
# # See PyCharm help at https://www.jetbrains.com/help/pycharm/

# 导包
import unittest
import os
from HTMLTestRunner import HTMLTestReportCN
import time
from common.sendEmail import SendEmail
from common.log import logger



# 1.查找测试用例,生成测试套件
def create_suite():
    # 获取测试用例的路径
    case_dir = os.path.dirname(__file__) + r"/testCase"
    # unittest.TestLoader()/unittest.defaultTestLoader
    # 1.1 实例化testloader()类
    loader = unittest.TestLoader()
    # 1.2 调用discover方法生成测试套件
    suite = loader.discover(start_dir=case_dir, pattern="Test*.py")
    # 1.3 返回测试套件
    logger.debug(suite)
    return suite


# 3. 清理报告
# 3.1 方案一: 全部干掉
def auto_clear():
    # os.dirlist()获取某个文件下全部文件
    dir = os.path.dirname(__file__) + r"/testReport"
    file_list = os.listdir(dir)
    file_list.sort()
    # print("=========>", file_list)
    logger.debug(file_list)
    logger.error(file_list)
    # 循环删除每一个文件os.remove()
    for i in file_list[:-3]:
        print(i)
        os.remove(dir + "/" + i)


if __name__ == '__main__':
    # 清理报告文件
    auto_clear()
    # 生成测试套件
    suite = create_suite()
    # print("--------------->", suite)
    logger.debug(suite)
    # 2. 运行测试套件生成测试报告
    # 获取时间
    cur_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
    # 2.1 创建报告文件名及路径
    report = os.path.dirname(__file__) + r"/testReport/" + cur_time + "report.html"
    # 2.2 以写入模式打开文件
    with open(report, "wb") as fp:
        # 2.3 实例化HtmlTestrunner得到一个runner对象
        runner = HTMLTestReportCN(stream=fp, title="接口自动化测试报告", description="接口测试结果", verbosity=2, tester="朕")
        # 2.4 调用实例方法执行测试套件
        runner.run(suite)
        # 2.5 关闭文件
    # 实例化
    se = SendEmail()
    # 发送邮件
    se.send(report)